package com.wawayaya.db.bookshelf;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.wawayaya.api.ApiResponseData;
import com.wawayaya.api.remote.ApiConstans;
import com.wawayaya.bean.Advert;
import com.wawayaya.bean.Area;
import com.wawayaya.bean.Banner;
import com.wawayaya.bean.BookShelf;
import com.wawayaya.bean.Books;
import com.wawayaya.bean.Config;
import com.wawayaya.bean.HomePage;
import com.wawayaya.bean.Notice;
import com.wawayaya.bean.Support;
import com.wawayaya.cache.UserDataCache;
import com.wawayaya.db.basedao.AdvertDao;
import com.wawayaya.db.basedao.BookShelfDao;
import com.wawayaya.db.basedao.BooksDao;
import com.wawayaya.db.basedao.HomePageDao;
import com.wawayaya.db.entitydao.AdvertEntityDao;
import com.wawayaya.db.entitydao.AreaEntityDao;
import com.wawayaya.db.entitydao.BannerEntityDao;
import com.wawayaya.db.entitydao.BookEntityDao;
import com.wawayaya.db.entitydao.BookShelfEntityDao;
import com.wawayaya.db.entitydao.ConfigEntityDao;
import com.wawayaya.db.entitydao.HomePageEntityDao;
import com.wawayaya.db.entitydao.NoticeEntityDao;
import com.wawayaya.db.entitydao.SupportEntityDao;
import com.wawayaya.util.TLog;
import com.wawayaya.util.TimeZoneUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by david on 15/8/24.
 * 数据存储/读取
 */
public class DBThread extends Thread{

    private  int   homepageCount = 5;
    private static final String  TAG = "DBThread";
    private  Handler  reqHandler;
    private  Handler  cHandler;

    public DBThread(){}

    public void setReqHandler(Handler reqHandler) {
        this.reqHandler = reqHandler;
    }

    public Handler getcHandler() {
        return cHandler;
    }
    @Override
    public void run() {
        super.run();
        Looper.prepare();
        cHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case ApiConstans.CONFIG:
                        configOperate((ApiResponseData) msg.obj);
                        break;
                    case ApiConstans.BOOKSHELF:
                        bookShelfOperate((ApiResponseData) msg.obj);
                        break;
                    case ApiConstans.BOOK:
                        bookOperate((ApiResponseData) msg.obj);
                        break;

                    case ApiConstans.ADVERT:
                        advertOperate((ApiResponseData) msg.obj);
                        break;
                    case ApiConstans.HOMEPAGE:
                        homepageOperate((ApiResponseData) msg.obj);
                        break;



                    case ApiConstans.SUPPORT:
                        supportOperate((ApiResponseData) msg.obj);
                        break;
                    case ApiConstans.BANNER:
                        bannerOperate((ApiResponseData) msg.obj);
                        break;
                    case ApiConstans.NOTICE:
                        noticeOperate((ApiResponseData) msg.obj);
                        break;
                    case ApiConstans.AREA:
                        areaOperate((ApiResponseData) msg.obj);
                        break;
                };
            }
        };
        Looper.loop();
    }

    private synchronized void  configOperate(final ApiResponseData  data){
        ConfigEntityDao configDao = new ConfigEntityDao();
        Config config =  new Config();
        try{
            if(null!=data.getUpdateAry()){
                for(int i=0;i<data.getUpdateAry().length();i++){
                    config =  ((Config)config.clone()).jsonToVO((JSONObject)data.getUpdateAry().get(i));
                    configDao.replaceEntity(config);
                    TLog.log(TAG, "返回 configOperate ...." + config.toString());
                }
            }
            if(null!=data.getDeleteAry()){
                for(int i=0;i<data.getDeleteAry().length();i++){
                    config =  ((Config)config.clone()).jsonToVO((JSONObject)data.getDeleteAry().get(i));
                    configDao.deleteEntityByKey(config.getValue());
                }
            }
            TLog.log("config存储完成......" + data.getServerTimestamp());

           // reqHandler.sendEmptyMessage(ApiConstans.BOOKSHELF);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }

    private synchronized void supportOperate(final ApiResponseData  data){
        SupportEntityDao supportFileDao = new SupportEntityDao();
        Support support =  new Support();
        try{
            if(null!=data.getUpdateAry()){

                for(int i=0;i<data.getUpdateAry().length();i++){
                    support = ((Support)support.clone()).jsonToVO((JSONObject)data.getUpdateAry().get(i));
                    supportFileDao.replaceEntity(support);
                    Log.e(TAG, "返回supportfile...." + support.toString());
                }
            }
            if(null!=data.getDeleteAry()){
                for(int i=0;i<data.getDeleteAry().length();i++){
                    JSONObject  jo=  data.getDeleteAry().optJSONObject(i);
                    supportFileDao.deleteEntityByKey(jo.optString("sfKey"));
                }
            }
         /*   Timestamp timestamp = new Timestamp();
            timestamp.setuId(data.getUid());
            timestamp.setSupportFile(data.getServerTimestamp());

            TimestampEntityDao timestampDao = new TimestampEntityDao();
            timestampDao.updateEntityBywhere(timestamp);*/
            //reqHandler.sendEmptyMessage(ApiConstans.MYBOOKSHELF);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }


    private synchronized void  noticeOperate(final ApiResponseData  data){
        NoticeEntityDao noticeDao = new NoticeEntityDao();
        Notice   versionNotice= null;
        try{
            if(null!=data.getUpdateAry()){
                Notice notice =  new Notice();
                for(int i=0;i<data.getUpdateAry().length();i++){
                    notice =  ((Notice)notice.clone()).jsonToVO((JSONObject)data.getUpdateAry().get(i));
                    noticeDao.replaceEntity(notice);
                }
            }
            if(null!=data.getDeleteAry()){
                for(int i=0;i<data.getDeleteAry().length();i++){
                    JSONObject  jo =data.getDeleteAry().optJSONObject(i);
                    noticeDao.deleteEntityByKey(jo.optLong("noticeId"));
                }
            }
           Message  message =  reqHandler.obtainMessage();
               message.what = ApiConstans.BANNER;
            reqHandler.sendMessage(message);
        }catch (JSONException e){
            e.printStackTrace();
        }

    }

    private synchronized  void  bookOperate(final ApiResponseData  data){
        BookEntityDao booksDao =new BookEntityDao();
        try{
            if(null!=data.getUpdateAry()){
                Books book =  new Books();
                for(int i=0;i<data.getUpdateAry().length();i++){
                    book = ((Books)book.clone()).jsonToVO((JSONObject)data.getUpdateAry().get(i));
                    booksDao.replaceEntity(book);
                     Log.e(TAG, "返回 book ...." + book.toString());
                }
            }
            if(null!=data.getDeleteAry()){
                for(int i=0;i<data.getDeleteAry().length();i++){
                    JSONObject  jo=  data.getDeleteAry().optJSONObject(i);
                    booksDao.deleteEntityByKey(jo.optInt("bookId"));
                }
            }

            Log.e(TAG, " book .complete..." + TimeZoneUtil.getCurentDate());
            //reqHandler.sendEmptyMessage(ApiConstans.ADVERT);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }


    /**
     * 未修改
     * @param data
     */
    private synchronized  void  bookShelfOperate(final ApiResponseData  data){
        BookShelfEntityDao shelfDao = new BookShelfEntityDao();
        try{

            if(null!=data.getUpdateAry()){
                BookShelf shelf =  new BookShelf();
                for(int i=0;i<data.getUpdateAry().length();i++){
                    shelf = ((BookShelf)shelf.clone()).jsonToVO((JSONObject)data.getUpdateAry().get(i));
                    shelfDao.replaceEntity(shelf);
                    Log.e(TAG, "返回 shelf ...." + shelf.toString());
                }
            }
            if(null!=data.getDeleteAry()){
                for(int i=0;i<data.getDeleteAry().length();i++){
                    JSONObject  jo=  data.getDeleteAry().optJSONObject(i);
                    shelfDao.deleteEntityByKey(jo.optLong("bsId"));
                }
            }
            TLog.log(TAG, "......shelf complete.......");
            //reqHandler.sendEmptyMessage(ApiConstans.BOOK);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }

    /**
     * 未修改
     * @param data
     */
    private synchronized  void  advertOperate(final ApiResponseData  data){
        AdvertEntityDao advertDao = new AdvertEntityDao();
        try{

            if(null!=data.getUpdateAry()){
                Advert advert =  new Advert();
                for(int i=0;i<data.getUpdateAry().length();i++){
                    advert = ((Advert)advert.clone()).jsonToVO((JSONObject)data.getUpdateAry().get(i));
                    advertDao.replaceEntity(advert);
                    Log.e(TAG, "返回 advert ...." + advert.toString());
                }
            }
            if(null!=data.getDeleteAry()){
                for(int i=0;i<data.getDeleteAry().length();i++){
                    JSONObject  jo=  data.getDeleteAry().optJSONObject(i);
                    advertDao.deleteEntityByKey(jo.optLong("bsId"));
                }
            }
            TLog.log(TAG, "......advert loading complete.......");
           // reqHandler.sendEmptyMessage(ApiConstans.HOMEPAGE);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }

    /**
     * 未修改
     * @param data
     */
    private synchronized  void  homepageOperate(final ApiResponseData  data){
        HomePageEntityDao shelfDao = new HomePageEntityDao();
        try{

            if(null!=data.getUpdateAry()){
                HomePage homepage =  new HomePage();
                for(int i=0;i<data.getUpdateAry().length();i++){
                    homepage = ((HomePage)homepage.clone()).jsonToVO((JSONObject)data.getUpdateAry().get(i));
                    shelfDao.replaceEntity(homepage);
                    Log.e(TAG, "返回 homepage ...." + homepage.toString());
                }
            }
            if(null!=data.getDeleteAry()){
                for(int i=0;i<data.getDeleteAry().length();i++){
                    JSONObject  jo=  data.getDeleteAry().optJSONObject(i);
                    shelfDao.deleteEntityByKey(jo.optLong("bsId"));
                }
            }
            TLog.log(TAG, "......homepage loading complete.......");
        }catch (JSONException e){
            e.printStackTrace();
        }
    }


    private synchronized void  bannerOperate(final ApiResponseData  data){
        BannerEntityDao bannerDao = new BannerEntityDao();
        Banner banner =  new Banner();
        try{
            if(null!= data.getUpdateAry()){

                for(int i=0;i< data.getUpdateAry().length();i++){
                    banner =  ((Banner)banner.clone()).jsonToVO((JSONObject) data.getUpdateAry().get(i));
                    Log.e("bannerOperate", "返回 bannerOperate........." + banner.toString());
                    bannerDao.insertOrReplaceByWhere(banner);
                }
            }
            if(null!=data.getDeleteAry()){
                //Log.e("DBManager","array...delete ......"+data.getDeleteAry());
                for(int i=0;i< data.getDeleteAry().length();i++){
                    banner =  ((Banner)banner.clone()).jsonToVO((JSONObject) data.getDeleteAry().get(i));
                    bannerDao.deleteEntityByKey(banner.getBannerId());
                }
            }
            reqHandler.sendEmptyMessage(ApiConstans.SUPPORT);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }

    private synchronized void  areaOperate(final ApiResponseData  data){
        AreaEntityDao areaEntityDao = new AreaEntityDao();
        Area area = new Area();
        try{
            if(null!=data.getUpdateAry()) {
                for (int i = 0; i < data.getUpdateAry().length(); i++) {
                    area = ((Area) area.clone()).jsonToVO((JSONObject) data.getUpdateAry().get(i));
                    areaEntityDao.replaceEntity(area);
                }
            }
            if(null!=data.getDeleteAry()){
                for(int i=0;i< data.getDeleteAry().length();i++){
                    area =  ((Area)area.clone()).jsonToVO((JSONObject)data.getDeleteAry().get(i));
                    areaEntityDao.deleteEntityByKey(area.getAreaId());
                    //Log.e(TAG, "返回 configOperate ...." + area.toString());
                }
            }
        }catch (JSONException e){
            e.printStackTrace();
        }
    }

    /**
     * 首页数据组拼
     */
    public    List<HomePage>   getHomepageData(){
        //初始化dao
        HomePageEntityDao  homePage =new HomePageEntityDao();
        BookShelfEntityDao bookShelfDao=new BookShelfEntityDao();
        BookEntityDao   bookDao = new BookEntityDao();
        List<HomePage>     homePageList = new ArrayList<>();
        AdvertEntityDao    advertDao = new AdvertEntityDao();

        //获取首页数据结构规则
        List<HomePage>     homePages = homePage.queryEntities("");

           TLog.log(TAG,"homePages LIST SIZE...."+homePages.size());
            for (int i=0;i< homePages.size();i++){
                final HomePage  home = homePages.get(i);
                //1. 书架
                if(home.getSectionType().intValue()==1){
                    boolean  flag = checkUserBsId(home.getItemId());
                    if(flag){
                        final   BookShelf  bookShelf =  getBooksByShelfId(home.getItemId(),homepageCount, bookShelfDao,bookDao);
                        home.setBookShelf(bookShelf);
                    }
                    homePageList.add(home);
                }

                /**
                 * 2. 栏目 ,根据sectionCode  :
                 *   (1) common-bs 对应shelf中 bsType:1
                 *   (2) prom-bs   对应shelf中 bsType:2
                 */
                else if(home.getSectionType().intValue()==2){
                    TLog.log(TAG,"homePages sectionType 2....");
                    if(home.getSectionCode().equals("common-bs")){   //查询 bsType 1
                        homePageList =  getBooksByBsType(homePageList,home,1, homepageCount, bookShelfDao,bookDao);
                    }
                    else if(home.getSectionCode().equals("prom-bs")){    //查询 bsType 1
                        homePageList =  getBooksByBsType(homePageList,home,2, homepageCount, bookShelfDao,bookDao);
                    }
                    else if(home.getSectionCode().equals("ad")){
                        homePageList = getAdvert(homePageList,home,advertDao);
                    }
                }
            }
            if(homePages.size()>0){
                  for(HomePage  homePage1 : homePages){
                      TLog.log("返回数据....."+homePage1.toString());
                  }
            }

        return homePages;

    }

    /**
     * 检查当前itemId，是否在用户基本信息中 书架bsIds中 是否存在
     * @param itemId
     * @return
     */
    private boolean  checkUserBsId(long itemId){
        boolean  flag = false;
        String  bsIds = UserDataCache.getInstance().getUserinfor().getBsIds();
        if(null!=bsIds && bsIds.length()>0){
            String []  bsArray = bsIds.split(",");
            for(int i=0;i<bsArray.length;i++){
                String  f=  bsArray[i];
                if(f.equals(String.valueOf(itemId))){
                    flag = true;
                }
            }
        }
        return flag;
    }

    /**
     * 获取当前书架的图书数据信息
     * @param bookShelfId
     * @param count
     */
    private  BookShelf  getBooksByShelfId(final long bookShelfId, int count,final BookShelfEntityDao bookShelfDao,final BookEntityDao bookDao){
        //根据bookShelfid查询对应的书架信息
      final   BookShelf bookShelf = bookShelfDao.queryEntityByWhere("where " + BookShelfDao.Properties.BsId.columnName + " =? ", String.valueOf(bookShelfId));
        if(null!=bookShelf){
            TLog.log(TAG,"当前书架的信息。。。。。"+bookShelf.toString());
            List<Books>  bookses=null;
            try{
                JSONArray  saleFlagArray = null;
                if(null!=bookShelf.getSaleFlag() ){
                    saleFlagArray = new JSONArray(bookShelf.getSaleFlag());
                }
                if(null!=saleFlagArray){
                    bookses= new ArrayList<>();
                    if(saleFlagArray.length()<count){
                        count = saleFlagArray.length();
                    }
                    for(int i=0;i<count;i++){
                        JSONObject saleFlag =   (JSONObject)saleFlagArray.get(i);
                        final  Books  books =  bookDao.queryEntityByWhere("where "+BooksDao.Properties.BookId.columnName+" = ?",
                                String.valueOf(saleFlag.optLong("bookId")));
                        bookses.add(books);
                    }
                }
                bookShelf.setBooksList(bookses);
            }catch (JSONException e){
                e.printStackTrace();
            }
        }
        return bookShelf;
    }

    /**
     * 获取当前bsType2 查询对应的书数据信息
     */
    private  List<HomePage>  getBooksByBsType(final List<HomePage> homePages,final  HomePage homePage,final int bsType2,
                                                int count,final BookShelfEntityDao bookShelfDao,final  BookEntityDao bookDao){
        //根据bookShelfid查询对应的书架信息
        final List<BookShelf> bookShelfList= bookShelfDao.queryEntities("where " + BookShelfDao.Properties.BsType2.columnName + " = ?", String.valueOf(bsType2));

        TLog.log(TAG,"当前bsType2 查询对应的书数据信息 当前书架的信息。。。。。"+bookShelfList.size());

        if(null!=bookShelfList){
             for(BookShelf  bookShelf:bookShelfList){
                 try{
                     final  List<Books>    bookses= new ArrayList<>();
                     JSONArray  saleFlagArray = null;

                     if(null!=bookShelf.getSaleFlag() ){
                         saleFlagArray = new JSONArray(bookShelf.getSaleFlag());
                     }

                     if(null!=saleFlagArray && saleFlagArray.length()>0){
                         if(saleFlagArray.length()<count){
                             count = saleFlagArray.length();
                         }
                         for(int i=0;i<count;i++){
                             JSONObject saleFlag =(JSONObject)saleFlagArray.get(i);
                             final  Books  books = bookDao.queryEntityByWhere("where " + BooksDao.Properties.BookId.columnName + " = ?",
                                     String.valueOf(saleFlag.optLong("bookId")));
                             bookses.add(books);
                         }
                     }
                     bookShelf.setBooksList(bookses);
                 }catch (JSONException e){
                     e.printStackTrace();
                 }
                 homePage.setBookShelf(bookShelf);
             }
            homePages.add(homePage);
        }
        return homePages;
    }

    /**
     * 广告栏 , 判断当前是第几栏，每栏取3条 ，如 第一栏: 1、2、3  第二栏: 4、5、6
     * @param homePages
     * @param homePage
     */
    private List<HomePage> getAdvert(final List<HomePage> homePages, final HomePage homePage,final AdvertEntityDao advertDao){
        //根据bookShelfid查询对应的书架信息
       //
        final List<Advert> adverts= advertDao.queryEntities("");

        if(null!=adverts){
            homePage.setAdverts(adverts);
        }

        homePages.add(homePage);
        return homePages;
    }


}
